<template>
  <view class="login-container">
    <!-- 头部Logo区域 -->
    <view class="header-section">
      <image class="logo" src="/static/logo.png" mode="aspectFit"></image>
      <text class="app-name">茶现武夷</text>
      <text class="slogan">{{ isLogin ? '欢迎回来' : '加入我们' }}</text>
    </view>

    <!-- 表单区域 -->
    <view class="form-container">
      <!-- 切换标签 -->
      <view class="tab-container">
        <view class="tab-item" :class="{ active: isLogin }" @click="switchToLogin">登录</view>
        <view class="tab-item" :class="{ active: !isLogin }" @click="switchToRegister">注册</view>
      </view>

      <!-- 登录表单 -->
      <view class="form-content" v-if="isLogin">
        <view class="input-group">
          <input class="input-field" type="text" placeholder="请输入用户名" v-model="loginForm.username" />
        </view>
        <view class="input-group">
          <view class="password-container">
            <input class="input-field" :type="showLoginPassword ? 'text' : 'password'" placeholder="请输入密码" v-model="loginForm.password"/>
          </view>
        </view>

        <view class="forgot-password" @click="handleForgotPassword">忘记密码？</view>
        <button class="submit-btn" @click="handleLogin">登录</button>
        <view class="switch-text">还没有账号？<text class="switch-link" @click="switchToRegister">立即注册</text></view>
      </view>

      <!-- 注册表单 -->
      <view class="form-content" v-else>
        <view class="input-group">
          <input class="input-field" type="text" placeholder="请输入用户名" v-model="registerForm.username" />
        </view>
        <view class="input-group">
          <view class="password-container">
            <input class="input-field" :type="showRegisterPassword ? 'text' : 'password'" placeholder="请设置密码（6-20位）" v-model="registerForm.password" maxlength="20" />
          </view>
        </view>
        <view class="input-group">
          <view class="password-container">
            <input class="input-field" :type="showConfirmPassword ? 'text' : 'password'" placeholder="请确认密码" v-model="registerForm.confirmPassword" maxlength="20" />
          </view>
        </view>
        <view class="agreement-container">
          <checkbox-group @change="onAgreementChange">
            <label class="agreement-item">
              <checkbox value="agree" :checked="agreedToTerms" />
              <text class="agreement-text">
                我已阅读并同意
                <text class="agreement-link" @click="showUserAgreement">《用户协议》</text>
                和
                <text class="agreement-link" @click="showPrivacyPolicy">《隐私政策》</text>
              </text>
            </label>
          </checkbox-group>
        </view>
        <button class="submit-btn" @click="handleRegister" :disabled="!agreedToTerms">注册</button>
        <view class="switch-text">已有账号？<text class="switch-link" @click="switchToLogin">立即登录</text></view>
      </view>
    </view>

    <!-- 加载提示 -->
    <view class="loading-overlay" v-if="loading">
      <view class="loading-spinner"></view>
      <text class="loading-text">{{ loadingText }}</text>
    </view>
  </view>
</template>

<script>
import md5 from '@/api/md5.js'

const BASE_URL = getApp().$vm.$global.baseURL

export default {
  data() {
    return {
      isLogin: true,
      loading: false,
      loadingText: '',
      showLoginPassword: false,
      showRegisterPassword: false,
      showConfirmPassword: false,
      agreedToTerms: false,
      loginForm: {
        username: '',
        password: ''
      },
      registerForm: {
        username: '',
        password: '',
        confirmPassword: ''
      }
    }
  },
  methods: {
    switchToLogin() {
      this.isLogin = true
      this.clearForms()
    },
    switchToRegister() {
      this.isLogin = false
      this.clearForms()
    },
    clearForms() {
      this.loginForm = { username: '', password: '' }
      this.registerForm = { username: '', password: '', confirmPassword: '' }
    },
    toggleLoginPassword() {
      this.showLoginPassword = !this.showLoginPassword
    },
    toggleRegisterPassword() {
      this.showRegisterPassword = !this.showRegisterPassword
    },
    onAgreementChange(e) {
      this.agreedToTerms = e.detail.value.includes('agree')
    },
    showUserAgreement() {
      uni.navigateTo({ url: '/pages/agreement/user-agreement' })
    },
    showPrivacyPolicy() {
      uni.navigateTo({ url: '/pages/agreement/privacy-policy' })
    },
    handleForgotPassword() {
      uni.navigateTo({ url: '/pages/forgot-password/forgot-password' })
    },

    async handleLogin() {
      if (!this.validateLoginForm()) return
      this.loading = true
      this.loadingText = '登录中...'

      try {
        const payload = {
          username: this.loginForm.username,
          password: md5(this.loginForm.password)
        }
        const res = await this.loginApi(payload)
        const user = res.data
        const token = user.token

        if (!token) throw new Error('未获取到 token')

        uni.setStorageSync('token', token)
        uni.setStorageSync('username', user.username)
        uni.setStorageSync('userInfo', {
          id: user.id,
          username: user.username,
          role: user.role,
          avatarUrl: user.avatarUrl
        })

        uni.showToast({ title: '登录成功', icon: 'success' })
        setTimeout(() => {
          uni.switchTab({ url: '/pages/index/index' })
        }, 1500)
      } catch (error) {
        uni.showToast({ title: error.message || '登录失败，请重试', icon: 'none' })
      } finally {
        this.loading = false
      }
    },

    async handleRegister() {
      if (!this.validateRegisterForm()) return
      this.loading = true
      this.loadingText = '注册中...'

      try {
        const payload = {
          username: this.registerForm.username,
          password: md5(this.registerForm.password)
        }
        const res = await this.registerApi(payload)
        uni.showToast({ title: '注册成功', icon: 'success' })
        setTimeout(() => {
          this.switchToLogin()
        }, 1500)
      } catch (error) {
        uni.showToast({ title: error.message || '注册失败，请重试', icon: 'none' })
      } finally {
        this.loading = false
      }
    },

    async loginApi(data) {
      return new Promise((resolve, reject) => {
        uni.request({
          url: `${BASE_URL}/login`,
          method: 'POST',
          data,
          header: { 'Content-Type': 'application/json' },
          success: (res) => {
            if (res.data && res.data.code === '200') {
              resolve(res.data)
            } else {
              reject(new Error(res.data?.msg || '登录失败'))
            }
          },
          fail: () => reject(new Error('网络异常，请稍后重试'))
        })
      })
    },

    async registerApi(data) {
      return new Promise((resolve, reject) => {
        uni.request({
          url: `${BASE_URL}/register`,
          method: 'POST',
          data,
          header: { 'Content-Type': 'application/json' },
          success: (res) => {
            if (1) {
              resolve(res.data)
            } else {
              reject(new Error(res.data.msg || '注册失败'))
            }
          },
          fail: () => reject(new Error('网络异常，请稍后重试'))
        })
      })
    },

    validateLoginForm() {
      if (!this.loginForm.username) {
        uni.showToast({ title: '请输入用户名', icon: 'none' })
        return false
      }
      if (!this.loginForm.password) {
        uni.showToast({ title: '请输入密码', icon: 'none' })
        return false
      }
      return true
    },

    validateRegisterForm() {
      if (!this.registerForm.username) {
        uni.showToast({ title: '请输入用户名', icon: 'none' })
        return false
      }
      if (!this.registerForm.password) {
        uni.showToast({ title: '请设置密码', icon: 'none' })
        return false
      }
      if (this.registerForm.password.length < 6) {
        uni.showToast({ title: '密码不能少于6位', icon: 'none' })
        return false
      }
      if (this.registerForm.password !== this.registerForm.confirmPassword) {
        uni.showToast({ title: '两次密码不一致', icon: 'none' })
        return false
      }
      return true
    }
  }
}
</script>




<style scoped>
.login-container {
  min-height: 100vh;
  background: #f5f5f5;
  padding: 40rpx;
  box-sizing: border-box;
}

/* 头部区域 */
.header-section {
  text-align: center;
  padding: 80rpx 0 60rpx;
}

.logo {
  width: 120rpx;
  height: 120rpx;
  margin: 0 auto 20rpx;
  display: block;
  border-radius: 12rpx;
}

.app-name {
  display: block;
  font-size: 36rpx;
  font-weight: bold;
  color: #333;
  margin-bottom: 10rpx;
}

.slogan {
  font-size: 24rpx;
  color: #666;
}

/* 表单容器 */
.form-container {
  background: #ffffff;
  border-radius: 16rpx;
  padding: 40rpx;
  box-shadow: 0 2rpx 10rpx rgba(0, 0, 0, 0.1);
}

/* 切换标签 */
.tab-container {
  display: flex;
  background: #f0f0f0;
  border-radius: 8rpx;
  margin-bottom: 40rpx;
  padding: 4rpx;
}

.tab-item {
  flex: 1;
  text-align: center;
  padding: 20rpx 0;
  font-size: 28rpx;
  color: #666;
  border-radius: 6rpx;
  transition: all 0.3s ease;
}

.tab-item.active {
  background: #388f4a;
  color: #ffffff;
}

/* 表单内容 */
.form-content {
  animation: fadeIn 0.3s ease;
}

@keyframes fadeIn {
  from { opacity: 0; }
  to { opacity: 1; }
}

.input-group {
  margin-bottom: 30rpx;
}

.input-field {
  width: 100%;
  height: 80rpx;
  padding: 0 20rpx;
  font-size: 28rpx;
  border: 2rpx solid #e0e0e0;
  border-radius: 8rpx;
  box-sizing: border-box;
  background: #ffffff;
}

.input-field:focus {
  border-color: #388f4a;
  outline: none;
}

.password-container {
  position: relative;
  display: flex;
  align-items: center;
}

.eye-icon {
  position: absolute;
  right: 20rpx;
  font-size: 32rpx;
  color: #999;
  cursor: pointer;
}

/* 忘记密码 */
.forgot-password {
  text-align: right;
  font-size: 24rpx;
  color: #388f4a;
  margin-bottom: 30rpx;
  cursor: pointer;
}

/* 协议容器 */
.agreement-container {
  margin-bottom: 30rpx;
}

.agreement-item {
  display: flex;
  align-items: flex-start;
  font-size: 24rpx;
  color: #666;
  line-height: 1.5;
}

.agreement-text {
  margin-left: 10rpx;
}

.agreement-link {
  color: #388f4a;
  text-decoration: underline;
}

/* 提交按钮 */
.submit-btn {
  width: 100%;
  height: 80rpx;
  background: #388f4a;
  color: #ffffff;
  border: none;
  border-radius: 8rpx;
  font-size: 30rpx;
  font-weight: 500;
  margin-bottom: 30rpx;
}

.submit-btn:disabled {
  background: #ccc;
  cursor: not-allowed;
}

/* 切换文本 */
.switch-text {
  text-align: center;
  font-size: 26rpx;
  color: #666;
}

.switch-link {
  color: #388f4a;
  font-weight: 500;
  cursor: pointer;
}

/* 加载遮罩 */
.loading-overlay {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: rgba(0, 0, 0, 0.7);
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  z-index: 9999;
}

.loading-spinner {
  width: 60rpx;
  height: 60rpx;
  border: 4rpx solid rgba(255, 255, 255, 0.3);
  border-top: 4rpx solid #388f4a;
  border-radius: 50%;
  animation: spin 1s linear infinite;
  margin-bottom: 20rpx;
}

@keyframes spin {
  0% { transform: rotate(0deg); }
  100% { transform: rotate(360deg); }
}

.loading-text {
  color: #ffffff;
  font-size: 26rpx;
}
</style>